package com.bosi.exmple.chat.handler;

import com.bosi.exmple.chat.ChatWebSocket;
import com.bosi.exmple.chat.SessionManager;
import com.bosi.exmple.chat.entity.User;
import com.bosi.exmple.chat.entity.WSRequest;
import com.bosi.exmple.chat.entity.WSResponse;
import com.bosi.message.Message;
import com.bosi.message.MessageService;
import com.bosi.exmple.ws.server.WebSocketSession;

import java.util.function.Function;

/**
 * 推送消息处理
 */
public class PushHandler implements Function<WSRequest,Object> {
    private final MessageService messageService;

    public PushHandler(MessageService messageService) {
        this.messageService = messageService;
    }


    @Override
    public Object apply(WSRequest req) {
        Message message = req.getMessage();
        Object to = message.getHeader().get("to");
        if(to != null){
            //私发
            WebSocketSession toSession = SessionManager.get(to);

            WSResponse res = WSResponse.createMessage(message);
            ChatWebSocket.sendMessage(res,toSession);
        }else {
            User user = (User) req.getSession().get("user");
            message.getHeader().put("game",user.getGame());
            messageService.publish(message);
        }

        return null;
    }
}
